//
//  PhotoWallViewController.m
//  CarFace
//
//  Created by dlios on 15-3-28.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "PhotoWallViewController.h"
#import "picWallpic.h"
#import "PicWallCollectionViewCell.h"
#import "DetailPhotoViewController.h"
@interface PhotoWallViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, assign)NSInteger set;
@property (nonatomic, retain)NSNumber *num;
@property (nonatomic, assign)NSInteger i;


@end

@implementation PhotoWallViewController


- (void)dealloc
{

    [_titleName release];
    [_carID release];
    [_pageStryleID release];
    [_arr release];
    [_collectionView release];
    [_num release];
    [super dealloc];
}




- (void)handleData1
{
   
   

    NSString *str = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.6/cars/pics-a2-pm2-v4.6.1-ss%@-sp0-cg%@-cl0-p%ld-s60-ft1.html",self.carID, self.pageStryleID,self.set];
    NSLog(@"%@",str);
    NSLog(@">>>>>>>%ld",self.set);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error = nil;
        NSJSONSerialization *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        self.num = [[result valueForKey:@"result"]valueForKey:@"pagecount"];
        self.i = [self.num integerValue];
        NSLog(@"huhuhuhu%ld",self.i);
        NSMutableArray *array = [[result valueForKey:@"result"]valueForKey:@"piclist"];
        for (NSDictionary *dic in array) {
            picWallpic *info = [[picWallpic alloc]initWithDictionary:dic];
            [self.arr addObject:info];
            [info release];
        }
        NSLog(@"________%ld",self.arr.count);
//
        
        [self.collectionView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败%@",error);
            }];
    
   
}

- (void)handleData
{
    
    //初始化数组
//    self.arr = [NSMutableArray array];
    NSString *str = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.6/cars/pics-a2-pm2-v4.6.1-ss%@-sp0-cg%@-cl0-p1-s60-ft1.html",self.carID, self.pageStryleID];
    NSLog(@"%@",str);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error = nil;
        NSJSONSerialization *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        NSMutableArray *array = [[result valueForKey:@"result"]valueForKey:@"piclist"];
        [self.arr removeAllObjects];
        for (NSDictionary *dic in array) {
            picWallpic *info = [[picWallpic alloc]initWithDictionary:dic];
            [self.arr addObject:info];
            [info release];
        }
        NSLog(@"________%ld",self.arr.count);
        
        [self.collectionView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败%@",error);
    }];
    
    

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.set = 2;
    //初始化数组
    self.arr = [NSMutableArray array];
    
    self.set = 1;
    [self handleData1];

    self.title = self.titleName;
//    self.view.backgroundColor = [UIColor magentaColor];
    
    
    /*************************布局collectionview********************/
    
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.itemSize = CGSizeMake((self.view.frame.size.width-30)/3, 100);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 5, 10, 5);
//    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-49) collectionViewLayout:flowLayout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
   
    
    [self.collectionView registerClass:[PicWallCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.view addSubview:self.collectionView];
    [flowLayout release];
    [_collectionView release];
    
    [self.collectionView addHeaderWithTarget:self action:@selector(addheader:)];
    [self.collectionView addFooterWithTarget:self action:@selector(footfresh:)];
    [self.collectionView setHeaderRefreshingText:@"刷新网络..."];
    [self.collectionView setFooterRefreshingText:@"网络加载中..."];
    
    
}
- (void)addheader:(UICollectionView *)collectionView
{
     __unsafe_unretained typeof(self) vc = self;
    [self.collectionView addHeaderWithCallback:^{
        [self handleData];
        
        // 进入刷新状态就会回调这个Block
        // 增加5条假数据
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.collectionView reloadData];
            // 结束刷新
            [vc.collectionView headerEndRefreshing];
        });
    } dateKey:@"collection"];
    // dateKey用于存储刷新时间，也可以不传值，可以保证不同界面拥有不同的刷新时间
    
#warning 自动刷新(一进入程序就下拉刷新)
    
    
    
//      [self.collectionView headerBeginRefreshing];
    
}




-(void)footfresh:(UICollectionView *)collectionView
{
    __unsafe_unretained typeof(self) vc = self;
    [self.collectionView addFooterWithCallback:^{
        
       
        if (self.set < self.i) {
            _set = _set + 1;
            [self handleData1];
        }
        
        [vc.collectionView footerEndRefreshing];
    }];
    
   
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [vc.collectionView reloadData];
        // 结束刷新
        [vc.collectionView footerEndRefreshing];
    });

}



/***************************collectionview的方法**********************/

//设置item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PicWallCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    picWallpic *info = [self.arr objectAtIndex:indexPath.row];
    cell.picAdress =  [info valueForKey:@"smallpic"];
    return cell;
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
 
    //将选中的cell序号传给下一页
    NSInteger order = indexPath.row;
    DetailPhotoViewController *detailPicVC = [[DetailPhotoViewController alloc]init];
    detailPicVC.order = order;
    detailPicVC.carID = self.carID;
    detailPicVC.pageStayID = self.pageStryleID;
    [self.navigationController pushViewController:detailPicVC animated:YES];
    [detailPicVC release];
 
    }






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
